<template>
  <a-modal
    v-model="visible"
    :title="form.id == null ? '新建': '编辑'"
    :after-close="afterClose"
    @ok="handleOk"
  >
    <a-form-model
      ref="form"
      :model="form"
      :rules="rules"
      :label-col="labelCol"
      :wrapper-col="wrapperCol"
    >
      <a-form-model-item ref="label" label="名称" prop="label">
        <a-input
          v-model="form.label"
        />
      </a-form-model-item>
      <a-form-model-item ref="code" label="编码" prop="code">
        <a-input
          v-model="form.code"
        />
      </a-form-model-item>
      <a-form-model-item ref="sort" label="排序" prop="sort">
        <a-input
          v-model="form.sort"
        />
      </a-form-model-item>
    </a-form-model>
  </a-modal>
</template>

<script>

import {saveDict} from '@/api/dict'

export default {
  data() {
    return {
      labelCol: {span: 4},
      wrapperCol: {span: 14},
      value: 1,
      visible: false,
      // form
      form: this.$form.createForm(this),
      rules: {
        label: [{required: true, message: '请输入名称', trigger: 'blur'}],
        code: [{required: true, message: '请输入编码', trigger: 'blur'}],
        sort: [{required: true, message: '请输入排序', trigger: 'blur'}]
      }
    }
  },
  methods: {
    handleOk(e) {
      this.$refs.form.validate(v => {
        if (v) {
          if (!this.form.id) this.form.createUser = this.$store.getters.id
          this.form.modifyUser = this.$store.getters.id
          saveDict(this.form).then(res => {
            if (res.code === '0') {
              this.$message.success('保存成功')
              this.visible = false
            } else {
              this.$message.error(res.message)
            }
          }).catch((reason) => {
            if (reason.response) {
              this.$message.error(reason.response.data.message)
            }
          })
        }
      })
    },
    initData(form) {
      this.visible = true
      this.form = form
    },
    afterClose() {
      this.$emit('close')
    }
  }
}
</script>
